package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class FollowController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(FollowController.class);
	
	@EJB 
	UserDaoLocal userDao;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String idFollowStr = req.getParameter("idfollow");
		int idFollow = Integer.parseInt(idFollowStr);
		
		int idUser = ((User)req.getSession().getAttribute("user")).getId();
		
		User userToFollow = userDao.findById(idFollow);
		User user = userDao.findById(idUser);
		
		userToFollow.getFollowers().add(user);
		user.getFollowedUsers().add(userToFollow);
		
		userDao.merge(userToFollow);
		userDao.merge(user);
		
		log.info(new Date() + " Korisnik[id]:" + idUser + " zapratio korisnika[id]:" +idFollowStr);
		
		resp.sendRedirect("./ViewUserController?id="+idFollowStr);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req,resp);
	}

}
